package com.example.lenovo.demo.presenter.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.example.lenovo.demo.CityActivity;
import com.example.lenovo.demo.CityFirstActivity;
import com.example.lenovo.demo.CityFirstHotActivity;
import com.example.lenovo.demo.MainMapActicity;
import com.example.lenovo.demo.MyApplication;
import com.example.lenovo.demo.R;
import com.example.lenovo.demo.StrategyActivity;
import com.example.lenovo.demo.WebViewActivity;
import com.example.lenovo.demo.model.databean.CityBean;
import com.example.lenovo.demo.view.customview.ImageButtonwithText;
import com.example.lenovo.demo.view.utils.GvHeightUtil;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2017/1/8.
 */

public class CityRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<Object> data;
    private Context context;
    private List<LinearLayout> city_Header_VpData;
    private final int headerItem=0;
    private final int city=1;
    private final int path=2;
    private final int hot=3;
    private final int record=4;
    private final int activitycollection=5;
    private LatLng latLng;
    private String id;
    private Bitmap bitmap;
    private BitmapDescriptor bitmaps ;
    private String msg;
    private CityBean.DataBean.DestinationBean destinationBean;
    private List<OverlayOptions> optionses;


    public CityRvAdapter(List<Object> data, Context context) {
        this.data = data;
        this.context = context;
        this.city_Header_VpData=new ArrayList<>();
        this.optionses=new ArrayList<>();

        this.bitmap=BitmapFactory.decodeResource(context.getResources(),R.drawable.location);
        initBitMap();
    }

    /**
     * 设置BitMap的大小
     *
     * */
    private void initBitMap() {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        // 设置想要的大小
        int newWidth = 40;
        int newHeight = 40;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
                true);

        bitmaps = BitmapDescriptorFactory.fromBitmap(bitmap);
    }

    @Override
    public int getItemViewType(int position) {
        if(position==0){
            return headerItem;
        }else {
            int type=-1;
            CityBean.DataBean.SectionsBean sectionsBean= (CityBean.DataBean.SectionsBean) data.get(position);
            switch (sectionsBean.getType()){
                case "Destination":
                    type=city;
                    break;
                case "Plan":
                    type=path;
                    break;
                case "SearchActivityCollectionDestinationEntity":
                    type=hot;
                    break;
                case "UserActivity":
                    type=record;
                    break;
                case "ActivityCollection":
                    type=activitycollection;
                    break;
            }
            return type;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder=null;
        switch (viewType){
            case headerItem:
                viewHolder=new HeaderVH(LayoutInflater.from(context).inflate(R.layout.city_header,parent,false));
                break;
            case city:
                viewHolder=new CityVH(LayoutInflater.from(context).inflate(R.layout.city_city,parent,false));
                break;
            case path:
                viewHolder=new PathVH(LayoutInflater.from(context).inflate(R.layout.city_path,parent,false));
                break;
            case hot:
                viewHolder=new HotVH(LayoutInflater.from(context).inflate(R.layout.city_hot,parent,false));
                break;
            case record:
                viewHolder=new RecordVH(LayoutInflater.from(context).inflate(R.layout.city_record,parent,false));
                break;
            case activitycollection:
                viewHolder=new HotVH(LayoutInflater.from(context).inflate(R.layout.city_hot,parent,false));
                break;
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        /**
         * 第一条为头部视图
         * */
        if(position==0){
            HeaderVH headerVH= (HeaderVH) holder;
            destinationBean= (CityBean.DataBean.DestinationBean) data.get(position);
            headerVH.name.setText(destinationBean.getName());
            headerVH.name_en.setText(destinationBean.getName_en());
            headerVH.imageView.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
            Picasso.with(context).load(destinationBean.getPhoto_url()).into(headerVH.imageView);
            List<CityBean.DataBean.GoodsBean> goodsBeens=destinationBean.getGoods();
            /**
             * 根据数据集合每四个生成一个布局，ViewPager的数据集合里存放此布局
             * */
            if(city_Header_VpData.size()==0){
                LinearLayout linearLayout=new LinearLayout(context);
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                for (int i = 0; i < goodsBeens.size(); i++) {
                    ImageButtonwithText it=new ImageButtonwithText(context);
                    it.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT,1));
                    it.setText(goodsBeens.get(i).getTitle());
                    if(goodsBeens.get(i).getUrl()!=null){
                        it.setTag(goodsBeens.get(i).getUrl());
                    }
                    it.getImageView().setImageResource(R.mipmap.ic_launcher);
                    it.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if(view.getTag()!=null){
                                String url= (String) view.getTag();
                                Intent intent=new Intent(context, WebViewActivity.class);
                                intent.putExtra("url",url);
                                context.startActivity(intent);
                            }else {
                                Intent intent=new Intent(context, StrategyActivity.class);
                                intent.putExtra("msg",destinationBean.getWikiDestinationBean().getId()+"");
                                context.startActivity(intent);
                            }


                        }
                    });




                    Glide.with(context).load(goodsBeens.get(i).getPhoto_url()).into(it.getImageView());
                    linearLayout.addView(it);
                    if(linearLayout.getChildCount()==4){
                        city_Header_VpData.add(linearLayout);
                        linearLayout=new LinearLayout(context);
                        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                    }

                }
                if(linearLayout.getChildCount()>0){
                    city_Header_VpData.add(linearLayout);
                }

                City_Header_VpAdapter adapter=new City_Header_VpAdapter(city_Header_VpData,context);

                headerVH.viewPager.setAdapter(adapter);
            }

            /**
             * 不是头部视图则根据数据解析的类型实现多布局
             * */
        }else {
            final CityBean.DataBean.SectionsBean sectionsBean= (CityBean.DataBean.SectionsBean) data.get(position);

            switch (sectionsBean.getType()){
                case "Destination":
                    CityVH cityVH= (CityVH) holder;
                    cityVH.textView.setText(sectionsBean.getTitle());
                    City_Destination_RvAdapter adapter=new City_Destination_RvAdapter(sectionsBean.getModels(),context);
                    LinearLayoutManager manager=new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false);
                    cityVH.recyclerView.setLayoutManager(manager);
                    cityVH.recyclerView.setAdapter(adapter);
                    cityVH.clickText.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(context, MainMapActicity.class);
                            intent.putExtra("msg",destinationBean.getId()+"");
                            context.startActivity(intent);
                        }
                    });
                    adapter.setOnItemClick(new City_Destination_RvAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(int index) {
                            Log.e("msg",sectionsBean.getModels().get(index).getId()+"");
                            Intent intent2=new Intent(context, CityFirstActivity.class);
                            intent2.putExtra("msg",sectionsBean.getModels().get(index).getId()+"");
                            context.startActivity(intent2);

                        }
                    });


                    break;
                case "Plan":
                    //标记radioButton的选中默认为零

                     final PathVH pathVH= (PathVH) holder;
                    UiSettings settings=pathVH.mapView.getMap().getUiSettings();
                    settings.setAllGesturesEnabled(false);   //关闭一切手势操作
                    settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
                    settings.setZoomGesturesEnabled(false);//获取是否允许缩放手势返回:是否允许缩放手势
                    final List<CityBean.DataBean.SectionsBean.ModelsBean> models=sectionsBean.getModels();


                    //  MyApplication.modelses.addAll(models);
                        /**
                         * 根据数据动态生成radioButton
                         * */
                        for (int i = 0; i < models.size(); i++) {
                            addRadioButton(pathVH.radioGroup,Integer.toString(sectionsBean.getModels().get(i).getDays_count())+"日行程",models.get(i),i);
                        }
                    /**
                     * 实现Map的点击跳转
                     * */
                    pathVH.mapView.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                        @Override
                        public void onMapClick(LatLng latLng) {
                            Bundle bundle=new Bundle();
                            bundle.putString("id",id);
                            Intent intent=new Intent(context, CityActivity.class);
                            intent.putExtras(bundle);
                            context.startActivity(intent);
                        }

                        @Override
                        public boolean onMapPoiClick(MapPoi mapPoi) {
                            return false;
                        }
                    });


                    /**
                     * 地图的默认显示标记物
                     * */
                    if(sectionsBean.getModels().get(0)!=null){
                        id=Integer.toString(models.get(0).getId());
                        final List<CityBean.DataBean.SectionsBean.ModelsBean.DaysBean> days=sectionsBean.getModels().get(0).getDays();
                        initMainLocation(pathVH.mapView,days.get(0).getPoints().get(0).getPoi().getLat(),days.get(0).getPoints().get(0).getPoi().getLng());
                        for (CityBean.DataBean.SectionsBean.ModelsBean.DaysBean day : days) {
                            List<CityBean.DataBean.SectionsBean.ModelsBean.DaysBean.PointsBean> pois=day.getPoints();
                            for (CityBean.DataBean.SectionsBean.ModelsBean.DaysBean.PointsBean point : pois) {
                                latLng=new LatLng(point.getPoi().getLat(),point.getPoi().getLng());
                                OverlayOptions option = new MarkerOptions()
                                        .position(latLng)
                                        .icon(bitmaps);
                                optionses.add(option);
                            }
                        }

                        /**
                         * 地图默认显示的提示框信息
                         * */
                        msg=Integer.toString(sectionsBean.getModels().get(0).getDays_count())+"天，"+optionses.size()+"条旅行计划";
                        pathVH.msg1.setText(sectionsBean.getModels().get(0).getTitle());
                        pathVH.msg2.setText(msg);
                        pathVH.mapView.getMap().addOverlays(optionses);


                    }


                    /**
                     * 监听radioGroup选中状态，并改变信息
                     * */
                    pathVH.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup radioGroup, int i) {
                            RadioButton radioButton= (RadioButton) radioGroup.findViewById(i);
                            CityBean.DataBean.SectionsBean.ModelsBean modelsBean= (CityBean.DataBean.SectionsBean.ModelsBean) radioButton.getTag();
                            id=Integer.toString(modelsBean.getId());

                                optionses.clear();
                                pathVH.mapView.getMap().clear();
                                List<CityBean.DataBean.SectionsBean.ModelsBean.DaysBean> days1=modelsBean.getDays();
                                for (CityBean.DataBean.SectionsBean.ModelsBean.DaysBean day : days1) {
                                    List<CityBean.DataBean.SectionsBean.ModelsBean.DaysBean.PointsBean> pois=day.getPoints();
                                    for (CityBean.DataBean.SectionsBean.ModelsBean.DaysBean.PointsBean point : pois) {
                                        latLng=new LatLng(point.getPoi().getLat(),point.getPoi().getLng());
                                        OverlayOptions option = new MarkerOptions()
                                                .position(latLng)
                                                .icon(bitmaps);
                                        optionses.add(option);
                                    }
                                }
                                if(sectionsBean.getModels().get(0)!=null){
                                    msg=Integer.toString(sectionsBean.getModels().get(0).getDays_count())+"天，"+optionses.size()+"条旅行计划";
                                }

                                pathVH.msg1.setText(modelsBean.getTitle());
                                pathVH.msg2.setText(msg);
                                pathVH.mapView.getMap().addOverlays(optionses);
                        }
                    });

                    break;
                /**
                 * 旅游榜单嵌套ListView
                 * */
                case "SearchActivityCollectionDestinationEntity":
                    HotVH hotVH= (HotVH) holder;
                    City_Hot_LvAdapter hotAdapter=new City_Hot_LvAdapter(sectionsBean.getModels(),context);
                    hotVH.listView.setAdapter(hotAdapter);
                    GvHeightUtil.setListViewHeightBasedOnChildren(hotVH.listView,0);
                    hotVH.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent=new Intent(context, CityFirstHotActivity.class);
                            Bundle bundle=new Bundle();
                            bundle.putInt("num",i);
                            bundle.putString("city",sectionsBean.getModels().get(0).getName());
                            bundle.putString("msg",sectionsBean.getModels().get(0).getId()+"");
                            intent.putExtras(bundle);
                            context.startActivity(intent);
                        }
                    });





                    break;
                case "ActivityCollection":
                    HotVH hotVH2= (HotVH) holder;
                    City_Hot_LvAdapter hotAdapter2=new City_Hot_LvAdapter(sectionsBean.getModels(),context);
                    hotVH2.listView.setAdapter(hotAdapter2);
                    GvHeightUtil.setListViewHeightBasedOnChildren(hotVH2.listView,0);
                    break;
                case "UserActivity":
                    CityBean.DataBean.SectionsBean.ModelsBean modelsBean =sectionsBean.getModels().get(0);
                    RecordVH recordVH= (RecordVH) holder;
                    recordVH.imgcount.setText(Integer.toString(modelsBean.getContents_count()));
                    recordVH.author.setText(modelsBean.getUserBean().getName());
                    recordVH.title.setText(modelsBean.getTopic());
                    recordVH.subtitle.setText(modelsBean.getDescription());
                    if(modelsBean.getContents()!=null&&modelsBean.getContents().size()>1){
                        Picasso.with(context).load(modelsBean.getContents().get(0).getPhoto_url())
                                .into(recordVH.imageView);
                    }
                    break;
            }
        }




    }

    private void addRadioButton(RadioGroup radioGroup, String s, CityBean.DataBean.SectionsBean.ModelsBean modelsBean,int i) {
        ViewGroup.LayoutParams layoutParams= new ViewGroup.LayoutParams(100, 55);
        RadioButton radioButton=new RadioButton(context);
        radioButton.setLayoutParams(layoutParams);
        radioButton.setGravity(Gravity.CENTER);
        radioButton.setFocusable(false);
        Bitmap bitmap=null;
        radioButton.setButtonDrawable(new BitmapDrawable(bitmap));
        radioButton.setGravity(Gravity.CENTER);
        radioButton.setBackgroundResource(R.drawable.city_plan_checked);
        radioButton.setTextColor(Color.BLACK);
        radioButton.setTag(modelsBean);
        radioButton.setText(s);
        radioGroup.addView(radioButton,i);
        RadioButton rb= (RadioButton) radioGroup.getChildAt(0);
        rb.setChecked(true);

    }

    private void initMainLocation(MapView mapView,double lat, double lng) {
        LatLng cenpt = new LatLng(lat,lng);
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .zoom(12)
                .build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        mapView.getMap().setMapStatus(mMapStatusUpdate);
    }

    /**
     * 代码方式加载RadioButton
     * */
//    private void initRb(RadioGroup radioGroup,String s) {
//        ViewGroup.LayoutParams layoutParams= new ViewGroup.LayoutParams(100, ViewGroup.LayoutParams.MATCH_PARENT);
//        RadioButton radioButton=new RadioButton(context);
//        radioButton.setLayoutParams(layoutParams);
//        radioButton.setGravity(Gravity.CENTER);
//        Bitmap bitmap=null;
//        radioButton.setButtonDrawable(new BitmapDrawable(bitmap));
//        radioButton.setGravity(Gravity.CENTER);
//        radioButton.setBackgroundResource(R.drawable.city_plan_checked);
//        radioButton.setTextColor(Color.BLACK);
//        radioButton.setText(s);
//        radioGroup.addView(radioButton);
//        RadioButton rb= (RadioButton) radioGroup.getChildAt(0);
//        rb.setChecked(true);
//
//
//    }

    @Override
    public int getItemCount() {
        return data==null?0:data.size();
    }

    class HeaderVH extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView name,name_en;
        ViewPager viewPager;
        public HeaderVH(View itemView) {
            super(itemView);
            imageView= (ImageView) itemView.findViewById(R.id.city_header_img);
            name= (TextView) itemView.findViewById(R.id.city_header_name);
            name_en= (TextView) itemView.findViewById(R.id.city_header_name_en);
            viewPager= (ViewPager) itemView.findViewById(R.id.city_header_vp);
        }
    }


    class CityVH extends RecyclerView.ViewHolder{
        TextView textView,clickText;
        RecyclerView recyclerView;
        public CityVH(View itemView) {
            super(itemView);
            textView= (TextView) itemView.findViewById(R.id.city_cityitem_tv);
            recyclerView= (RecyclerView) itemView.findViewById(R.id.city_cityitem_rv);
            clickText= (TextView) itemView.findViewById(R.id.city_city_text);
        }
    }

    class PathVH extends RecyclerView.ViewHolder {
        TextView msg1,msg2;
        MapView mapView;
        RadioGroup radioGroup;
        public PathVH(View itemView) {
            super(itemView);
            radioGroup= (RadioGroup) itemView.findViewById(R.id.city_pathitem_rg);
            mapView= (MapView) itemView.findViewById(R.id.city_path_mapview);
            msg1= (TextView) itemView.findViewById(R.id.city_path_msg1);
            msg2= (TextView) itemView.findViewById(R.id.city_path_msg2);
        }
    }

    class HotVH extends RecyclerView.ViewHolder{
        ListView listView;

        public HotVH(View itemView) {
            super(itemView);
            listView= (ListView) itemView.findViewById(R.id.city_hotitem_lv);
        }
    }
    class RecordVH extends RecyclerView.ViewHolder{
        TextView imgcount,author,title,subtitle,allnote;
        ImageView imageView;
        public RecordVH(View itemView) {
            super(itemView);
            imgcount= (TextView) itemView.findViewById(R.id.record_tv_imgcount);
            author= (TextView) itemView.findViewById(R.id.record_tv_author);
            title= (TextView) itemView.findViewById(R.id.record_tv_title);
            subtitle= (TextView) itemView.findViewById(R.id.record_tv_subtitle);
            allnote= (TextView) itemView.findViewById(R.id.record_tv_allnote);
            imageView= (ImageView) itemView.findViewById(R.id.record_img_imageview);

        }
    }


}
